from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
import random
from meixixi.libs.captcha.captcha import captcha
from celery_tasks.sms.tasks import send_msg_code


class ImageCodeView(View):
    def get(self, request, image_code_id):
        name, text, image_data = captcha.generate_captcha()
        redis_conn = get_redis_connection('code')
        redis_conn.set('image_code_%s' % image_code_id, text,300)
        response = http.HttpResponse(image_data)
        response['Content-Type'] = 'image/png'
        return response


class SMSCodeView(View):
    def get(self,request,mobile):
        image_code = request.GET .get('image_code')
        image_code_id = request.GET.get('image_code_id')

        redis_conn = get_redis_connection('code')
        flag = redis_conn.get('send_flag_%s' % mobile)

        if flag:
            return http.JsonResponse({'errmsg': '请勿频繁发送短信'}, status=400)

        if not all([image_code, image_code_id]):
            return http.JsonResponse({'errmsg':'参数不全'}, status=400)

        redis_conn = get_redis_connection('code')
        redis_image_code = redis_conn.get('image_code_%s'%image_code_id)

        if not redis_image_code:
            return http.JsonResponse({'errmsg':'图片验证码已过期'}, status=400)
            redis_conn.delete('image_code_%s'%image_code_id)

        if image_code.lower() != redis_image_code.decode().lower():
            return http.JsonResponse({'errmsg':'图片验证码错误'}, status=400)

        sms_code = '%06d' % random.randint(0, 999999)
        ccp = CCP()
        ccp.send_template_sms(mobile, [sms_code, 5], 1)

        redis_conn.set('sms_code_%s'%mobile, sms_code, 300)

        return http.JsonResponse({'code':0, 'errmsg':'发送成功'})


        redis_conn.set('send_flag_%s' % mobile,'flag', 60)

        return http.JsonResponse({'code':0, 'errmsg':'发送成功'})

        pipeline = redis_conn.pipeline()
        pipeline.set('sms_code_%s' % mobile, 'flag', 60)
        pipeline.execute()


        send_msg_code.delay(mobile, sms_code)